import Vue from 'vue'
import VueRouter from 'vue-router'
import Films from '@/views/Films'
import Center from '@/views/Center'
import Cinemas from '@/views/Cinemas'
import Search from '@/views/Search'
import Nowplaying from '@/views/films/Nowplaying'
import Comingsoon from '@/views/films/Comingsoon'
import Detail from '@/views/Detail'
import Order from '@/views/Order'
import Login from '@/views/Login'
import City from '@/views/City'
import Register from '@/views/Register'

Vue.use(VueRouter)//注册路由插件  两个全局 router-view  router-link


// 配置表
const routes = [
  {
    path: '/films',
    component: Films,

    /* 嵌套路由 */
    children:[
        {
          path: '/films/nowplaying',
          component: Nowplaying
        },
        {
          path: '/films/comingsoon',
          component: Comingsoon
        },
        {
          path: '/films',
          redirect: '/films/nowplaying'
        },
    ]
  },
  {
    name:'bee', //命名路由
    path: '/detail/:id',/* 动态二级路由 */
    component: Detail
  },
  {
    path: '/cinemas',
    component: Cinemas
  },
  {
    path: '/city',
    component: City
  },
  {
    path: '/cinemas/search',
    component: Search
  },
  {
    path: '/center',
    component: Center,
    meta:{
      isBeeRequired:true
    }
  },
  {
    path: '/order',
    component: Order,
    meta:{
      isBeeRequired:true
    }
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component:Register
  },
  /* 重定向 */
  {
    path: '*',
    redirect:'/films'
  }
]

const router = new VueRouter({
  /* 使用history模式，让url看起来像正常的url；符合要求；第三分享时候更加方便；hash模式是#；
  缺点：这样会让浏览器不知道你是后端还是前端路由，
  解决：url匹配不到任何资源的时候，让后端，赋予一个index前端页面*/
  mode:'hash',
  routes
})


// 全局拦截 路由拦截守卫  是否需要拦截验证  第一个参数to是跳转的 第二个from从哪里来  第三个next下一步处理 放行
router.beforeEach((to, from, next) => {
  console.log(to);

  // 是否需要授权认证
  if(to.meta.isBeeRequired){
    // 判断 本地存储是否token  
    if(localStorage.getItem('token')){
      next()
    }else{
      next({
        path:'/login',
        /* 获取他到哪里来的 */
        query: { redirect: to.fullPath }
      })
    }
  }else{
    next()
  }
  
})

export default router


